package cn.snoworld.service;

import cn.snoworld.entity.Picture;
import cn.snoworld.mapper.FileUploadMapper;
import cn.snoworld.utils.CosUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author zxj
 * 上传图片服务层
 */
@Service
public class FileUploadServiceImpl extends ServiceImpl<FileUploadMapper, Picture> implements FileUploadService{

    @Autowired
    private FileUploadMapper uploadMapper;

    @Value("${atzxj.secretId}")
    private String secretId;
    @Value("${atzxj.secretKey}")
    private String secretKey;
    @Value("${atzxj.bucketName}")
    private String bucketName;

    /**
     * 文件上传接口
     *
     * @param file 文件
     * @return Boolean
     */
    @Override
    public Boolean upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String[] split = filename.split("\\.");
        //原始名称
        String name = split[0];
        //后缀名
        String suffix = split[1];
        //对象存储中的名称
        String saveName = UUID.randomUUID().toString().replaceAll("\\-", "");
        //上传
        Boolean isUploaded = CosUtil.uploadPicture(file, suffix, saveName,secretId,secretKey,bucketName);
        if (Boolean.TRUE.equals(isUploaded)) {
            //若上传成功 则保存到数据库中
            Picture picture = new Picture();
            picture.setOriginName(name);
            picture.setUuid(saveName);
            picture.setContentType(suffix);
            int insert = uploadMapper.insert(picture);
            return insert > 0;
        }
        return false;
    }
}
